<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>留言板</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 20px;
    }

    h1 {
      text-align: center;
    }

    #app {
      max-width: 600px;
      margin: 0 auto;
    }

    input[type="text"] {
      width: 100%;
      padding: 8px;
      margin-bottom: 10px;
    }

    .button-container {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
    }

    .search-button,
    .add-message-button,
    .logout-button,
    .export-button { /* Added */
      background-color: #4CAF50;
      color: white;
      border: none;
      border-radius: 4px;
      padding: 8px 16px;
      font-size: 14px;
      cursor: pointer;
    }

    .logout-button {
      background-color: #f44336;
    }

    .pagination {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 10px;
    }

    .pagination button {
      margin: 0 5px;
    }

    .message {
      border: 1px solid #ccc;
      border-radius: 5px;
      padding: 10px;
      margin-bottom: 10px;
    }

    .message p:first-child {
      font-weight: bold;
      margin-bottom: 5px;
    }

    .create-time {
      font-size: 12px;
      color: #777;
    }

    .add-message {
      margin-top: 10px;
    }

    .add-message textarea {
      width: 100%;
      padding: 8px;
      margin-bottom: 10px;
      resize: vertical;
    }

    .add-message button {
      background-color: #4CAF50;
      color: white;
      border: none;
      border-radius: 4px;
      padding: 8px 16px;
      font-size: 14px;
      cursor: pointer;
    }

    .add-message button:hover {
      background-color: #45a049;
    }
  </style>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
  <h1>留言板</h1>
  <div class="button-container">
    <div>
      <input type="text" v-model="searchKeyword" placeholder="Enter keyword">
      <button @click="searchMessages" class="search-button">搜索</button>
    </div>
    <div>
      <button @click="showAddMessage" class="add-message-button">添加留言</button>
      <button @click="logout" class="logout-button">退出登录</button>
      <button @click="exportToExcel" class="export-button">导出Excel</button> <!-- Added -->
    </div>
  </div>

  <div v-for="message in displayedMessages" :key="message.id" class="message">
    <p>{{ message.username }}:</p>
    <p>{{ message.content }}</p>
    <p class="create-time">创建时间: {{ formatTime(message.createTime) }}</p>
  </div>
  <div v-if="showAddMessageInput" class="add-message">
    <textarea v-model="newMessage.content"></textarea>
    <button @click="addMessage">提交</button>
  </div>
  <div class="pagination">
    <button @click="previousPage" :disabled="pageNo === 1">上一页</button>
    <p>当前页码: {{ pageNo }}</p>
    <button @click="nextPage">下一页</button>
  </div>
</div>

<script>
  new Vue({
    el: '#app',
    data: {
      messages: [],
      showAddMessageInput: false,
      newMessage: {
        content: '',
        create_time: ''
      },
      pageNo: 1,
      pageSize: 5,
      searchKeyword: ''
    },
    computed: {
      displayedMessages() {
        if (this.searchKeyword.trim() !== '') {
          return this.messages.filter(message => {
            return (
                    message.username.toLowerCase().includes(this.searchKeyword.toLowerCase()) ||
                    message.content.toLowerCase().includes(this.searchKeyword.toLowerCase())
            );
          });
        } else {
          return this.messages;
        }
      }
    },
    mounted() {
      const tokenCookie = document.cookie.split(';').find(cookie => cookie.trim().startsWith('token='));
      if (tokenCookie) {
        const token = tokenCookie.split('=')[1].trim();
        axios.defaults.headers.common['Authorization'] = token;
      }
      const urlParams = new URLSearchParams(window.location.search);
      const keyword = urlParams.get('keyword');
      if (keyword) {
        this.searchKeyword = keyword;
      }
      this.getMessageList();
    },
    methods: {
      logout() {
        document.cookie = "token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
        window.location.href = "/login.html";
      },
      getMessageList() {
        axios.get(`/message/getListByPage?pageNo=${this.pageNo}&pageSize=${this.pageSize}`)
                .then(response => {
                  this.messages = response.data;
                })
                .catch(error => {
                  console.error(error);
                });
      },
      showAddMessage() {
        const tokenCookie = document.cookie.split(';').find(cookie => cookie.trim().startsWith('token='));
        if (tokenCookie) {
          this.showAddMessageInput = true;
        } else {
          window.location.href = '/login.html';
        }
      },
      addMessage() {
        if (this.newMessage.content !== '') {
          const config = {
            headers: {
              'Content-Type': 'application/json'
            }
          };
          axios.post('/message/add', this.newMessage, config)
                  .then(response => {
                    this.messages.push(response.data);
                    this.newMessage.content = '';
                    this.showAddMessageInput = false;
                    this.getMessageList();
                  })
                  .catch(error => {
                    console.error(error);
                  });
        }
      },
      previousPage() {
        if (this.pageNo > 1) {
          this.pageNo--;
          this.getMessageList();
        }
      },
      nextPage() {
        this.pageNo++;
        this.getMessageList();
      },
      searchMessages() {
        if (this.searchKeyword.trim() !== '') {
          axios.get(`/message/search?keyword=${this.searchKeyword}`)
                  .then(response => {
                    this.messages = response.data;
                    this.pageNo = 1;
                  })
                  .catch(error => {
                    console.error(error);
                  });
        } else {
          this.getMessageList();
        }
      },
      formatTime(createTime) {
        const date = new Date(createTime);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      },
      exportToExcel() {
        // 判断用户是否登录
        const tokenCookie = document.cookie.split(';').find(cookie => cookie.trim().startsWith('token='));
        if (!tokenCookie) {
          // 如果用户没有登录，则跳转到登录页面
          window.location.href = '/login.html';
          return; // 结束函数执行
        }

        // Prompt user for file name
        const fileName = prompt("Enter the file name:");
        if (!fileName) {
          return; // 如果用户取消输入文件名，则结束函数执行
        }

        // Create a temporary link element
        const link = document.createElement('a');

        // Send the file name to the backend API
        axios.get(`/message/exportExcel?fileName=${fileName}`, { responseType: 'blob' })
                .then(response => {
                  // Create a blob object from the response data
                  const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

                  /*// Create a temporary URL for the blob object
                  const url = URL.createObjectURL(blob);

                  // Set the link properties
                  link.href = url;
                  link.download = `${fileName}`;

                  // Programmatically click the link to trigger the file download
                  link.click();

                  // Clean up the temporary URL and remove the link element
                  URL.revokeObjectURL(url);
                  link.remove();*/
                  alert("下载成功")
                })
                .catch(error => {
                  console.error(error);
                });
      }
    }
  });
</script>
</body>
</html>
